'use strict'

$(function () {
    $.get(`${baseUrl}/books`, (res) => {
        console.log(res);
        list(res)
    })
})

// 查找按钮
function btnFind() {
    let keyword = $('#keyword').val();
    $.get(`${baseUrl}/books?keyword=${keyword}`, (res) => {
        $('.book').html('');
        list(res);
    })
}

// 新增按钮
function btnAdd() {
    window.location.href = './addOrEidt.html';
}

// 编辑按钮
function btnEidt(id) {
    window.location.href = `./addOrEidt.html?id=${id}`;
}

// 删除按钮
function btnDel(id) {
    if (confirm('确认删除？')) {
        $.ajax({
            type: "delete",
            url: `${baseUrl}/books/${id}`,
            success: (res) => {
                if (res.code === 1000) {
                    $(`[key=${id}]`).remove();
                    alert(res.msg);
                } else {
                    alert(res.msg)
                }
            }
        })
    }

}


// 遍历数据
function list(data) {
    $('#index_tb').html('')
    data.forEach(item => {
        // console.log(item);
        let html = `
        <tr class="book" key="${item.id}">
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.price}</td>
            <td>${item.press}</td>
            <td>
                <input type="button" value="编辑" id="btnEidt" onclick="btnEidt(${item.id})">
                <input type="button" value="删除" id="btnDel" onclick="btnDel(${item.id})">
            </td>
        </tr>
        `
        $('#index_tb').append(html);
    });
}